# -*- coding: utf-8 -*-

from robot.api import logger
from robot.api.deco import keyword
import redis

from robot.utils import ConnectionCache

from .UtilLib import UtilLib

class RedisLibrary(object):

    def __init__(self):
        self._connections = ConnectionCache()
        self.u = UtilLib()

    @keyword('Connect To Redis')
    def connect_to_redis(self, connect_string, aliasPre):

        """Connect to the Redis server
        Arguments:
            - connect_string: the connect string to redis
        Retun redis connect object
        Examples:
        | Connect To Redis | "host=172.0.0.1,port=6379,db=1,password='12345'" | demo_alias |
        """
        alias = self._get_alias_name(aliasPre)
        redis_connect_dict = {}
        for i in connect_string.split(",")[:]:
            k = i.split("=")[0]
            v = i.split("=")[1]
            redis_connect_dict[k] = v

        host = redis_connect_dict['host']
        port = redis_connect_dict['port']
        db = redis_connect_dict['db']
        password = redis_connect_dict['password']

        try:
            redis_conn = redis.StrictRedis(host=host, port=port, db=db, password=password)
        except Exception as ex:
            logger.error(str(ex))
            raise Exception(str(ex))
        conn = self._connections.register(redis_conn, alias=alias)
        logger.info("[REDIS建立连接] 位置: {0}, 别名: {1}, 地址: {2}".format(conn, alias, connect_string))

        return conn

    @keyword('Close Redis')
    def close_redis(self, aliasPre):
        """
        关闭redis连接
        | Close Redis | local_alias |
        """
        alias = self._get_alias_name(aliasPre)
        redis_conn = self._connections.get_connection(alias_or_index=alias)
        redis_conn.connection_pool.disconnect
        logger.info("[REDIS关闭连接] 数据库: {}".format(alias))

    @keyword('Delete Key From Redis')
    def delete_key_from_redis(self, aliasPre, key):
        """ Delete data from Redis
        Arguments:
            - redis_conn: Redis connection object
            - key: String keyword to find.
        Examples:
        | Delete From Redis |  local_alias | BARCODE |
        """
        alias = self._get_alias_name(aliasPre)
        logger.info(("[REDIS] 执行删除key：{0}".format(key)))
        redis_conn = self._connections.get_connection(alias_or_index=alias)
        redis_conn.delete(key)
        if not redis_conn.exists(key):
            logger.info(("[REDIS] 成功删除key：{0}".format(key)))
        return redis_conn

    @keyword('Redis Key Should Be Exist')
    def redis_key_should_be_exist(self, aliasPre, key, ttlTime=-1):
        """ Keyword will fail if specify key doesn't exist in Redis
        Arguments:
            - redis_conn: Redis connection object
            - key: String keyword to find.
        Examples:
        | Redis Key Should Be Exist | local_alias | demo_key | -1 |
        """
        alias = self._get_alias_name(aliasPre)
        redis_conn = self._connections.get_connection(alias_or_index=alias)
        # redis判断返回值不是None，是0
        if redis_conn.exists(key) == 0:
            logger.info("[检查key存在] key: {0} 不存在，校验不通过".format(key))
            raise AssertionError
        
        ttlCheckTime = int(ttlTime)
        keyTimeM = redis_conn.ttl(key) / 60

        if ttlCheckTime != -1:
            if keyTimeM != ttlCheckTime:
                logger.info("[检查key过期] key: {0}, 期望过期时间: {1}分钟, 实际过期时间: {2}分钟， 校验不通过".format(key, ttlCheckTime, keyTimeM))
                raise AssertionError

        logger.info("[检查key存在] key: {0} 存在，过期时间: {1} 分钟，校验通过".format(key, keyTimeM))

    @keyword('Redis Key Should Not Be Exist')
    def redis_key_should_not_be_exist(self, aliasPre, key):
        """ Keyword will fail if specify key exist in Redis
        Arguments:
            - redis_conn: Redis connection object
            - key: String keyword to find.
        Examples:
        | Redis Key Should Not Be Exist | local_alias | BARCODE|1234567890 |
        """
        alias = self._get_alias_name(aliasPre)
        redis_conn = self._connections.get_connection(alias_or_index=alias)
        
        if redis_conn.exists(key) != 0:
            logger.info("[检查key不存在] key: {0} 存在，校验不通过".format(key))
            raise AssertionError
        else:
            logger.info("[检查key不存在] key: {0} 不存在，校验通过".format(key))

    def _get_alias_name(self, aliasPre):

        return aliasPre + "_" + self.u.get_venv()